package com.spzx.product.service.impl;

import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.product.service.ITestService;
import io.jsonwebtoken.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: TestServiceImpl
 * Package: com.spzx.product.service.impl
 * Description:
 */
@Service
public class TestServiceImpl implements ITestService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void testLock() {
        //获取锁
        String uuid = UUID.randomUUID().toString();
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 1, TimeUnit.SECONDS);
        if (flag) {
            this.renewTime("lock", uuid, 1L);
            //获取到锁后
            String value = stringRedisTemplate.opsForValue().get("num");
            if (StringUtils.isBlank(value)) {
                return;
            }
            int num = Integer.parseInt(value);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            stringRedisTemplate.opsForValue().set("num", String.valueOf(++num));

            //使用lua脚本判断锁的身份信息并释放锁
            String script = """
                    if 
                        redis.call('get', KEYS[1]) == ARGV[1] 
                    then 
                        return redis.call('del', KEYS[1]) 
                    else 
                        return 0 
                    end
                    """;
            stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList("lock"), uuid);
        } else {
            //没有获取到锁,睡一会继续获取
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            testLock();
        }


    }

    private void renewTime(String lockName, String uuid, Long expire) {
        String script = """
                if
                    redis.call('get', KEYS[1]) == ARGV[1]
                then 
                    redis.call('expire', KEYS[1], ARGV[2]); 
                    return 1; 
                else 
                    return 0; 
                end
                """;
        new Thread(() -> {
            while (stringRedisTemplate.execute(
                    new DefaultRedisScript<>(script, Boolean.class),
                    Arrays.asList(lockName),
                    uuid,
                    expire.toString())) {
                try {
                    //业务逻辑要求在达到过期时间的2/3的时候续期
                    Thread.sleep(expire * 2 / 3 * 1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }).start();
    }

}
